package com.pf.service.impl;

import com.google.common.collect.Lists;
import com.pf.dto.MailReq;
import com.pf.dto.UserScore;
import com.pf.service.MailService;
import com.pf.utils.ExcelUtils;
import com.pf.utils.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author PF
 * @date 2021/6/24 20:43
 * @Version 1.0
 */
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private MailUtils mailUtils;

    @Override
    public void sendTextMail() {
        List<String> toUsers = Lists.newArrayList("1968438358@qq.com");
        List<String> ccUsers = Lists.newArrayList("2478926200@qq.com");
        String subject = "文本邮件标题";
        String content = "文本邮件内容";
        mailUtils.sendTextMail(toUsers, ccUsers, subject, content);
    }

    @Override
    public void sendHTMLMail() {
        List<String> toUsers = Lists.newArrayList("1968438358@qq.com");
        List<String> ccUsers = Lists.newArrayList("2478926200@qq.com");
        String subject = "HTML邮件标题";
        String content = new StringBuilder()
                .append("<html>")
                .append("<body>")
                .append("<h1>邮件内容</h1>")
                .append("<p>我是html邮件内容</p>")
                .append("</body>")
                .append("</html>").toString();
        mailUtils.sendTextMail(toUsers, ccUsers, subject, content);
    }

    @Override
    public void sendInlineResourceMail() {
        List<String> toUsers = Lists.newArrayList("1968438358@qq.com");
        List<String> ccUsers = Lists.newArrayList("2478926200@qq.com");
        String subject = "嵌入静态资源的邮件标题";
        String cotentId = "test001";
        String content = "<html><body>这是有图片的邮件：<img src=\'cid:" + cotentId + "\' ></body></html>";
        // 读取 static下的图片信息
        ClassPathResource resource = new ClassPathResource("/static/a.jpg");
        try {
            String filePath = resource.getFile().getPath();
            mailUtils.sendInlineResourceMail(toUsers, ccUsers, subject, cotentId, content, filePath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void sendAttachmentsMail() {
        List<String> toUsers = Lists.newArrayList("1968438358@qq.com");
        List<String> ccUsers = Lists.newArrayList("2478926200@qq.com");
        String subject = "带有附件的邮件标题";
        String content = "带有附件的邮件内容信息";
        // 读取 static下的图片信息
        ClassPathResource resource = new ClassPathResource("/static/a.jpg");
        try {
            String filePath = resource.getFile().getPath();
            mailUtils.sendAttachmentsMail(toUsers, ccUsers, subject, content, filePath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void sendTemplateFreemarker() {
        List<String> toUsers = Lists.newArrayList("1968438358@qq.com");
        List<String> ccUsers = Lists.newArrayList("2478926200@qq.com");
        String subject = "freemarker模板的邮件标题";
        // 模板数据
        Map<String, Object> data = new HashMap<>(2);
        UserScore score1 = UserScore.builder().id(1).subject("数学").score(120).build();
        UserScore score2 = UserScore.builder().id(1).subject("语文").score(130).build();
        UserScore score3 = UserScore.builder().id(1).subject("英文").score(140).build();
        ArrayList<UserScore> userScores = Lists.newArrayList(score1, score2, score3);
        data.put("username", "张三");
        data.put("userScores", userScores);

        String freemarkerName = "template.ftl";
        mailUtils.sendTemplateFreemarker(toUsers, ccUsers, subject, data, freemarkerName);
    }

    @Override
    public void sendTemplateThymeleaf() {

        List<String> toUsers = Lists.newArrayList("1968438358@qq.com");
        List<String> ccUsers = Lists.newArrayList("2478926200@qq.com");
        String subject = "thymeleaf模板的邮件标题";
        // 模板数据
        Map<String, Object> data = new HashMap<>(2);
        UserScore score1 = UserScore.builder().id(1).subject("数学").score(120).build();
        UserScore score2 = UserScore.builder().id(1).subject("语文").score(130).build();
        UserScore score3 = UserScore.builder().id(1).subject("英文").score(140).build();
        ArrayList<UserScore> userScores = Lists.newArrayList(score1, score2, score3);
        data.put("username", "张三");
        data.put("userScores", userScores);

        String freemarkerName = "template";
        mailUtils.sendTemplateThymeleaf(toUsers, ccUsers, subject, data, freemarkerName);
    }

    @Override
    public void sendExcelMail() {
        // 创建excel 输入流
        byte[] bytes = ExcelUtils.createExcel();
        List<String> toUsers = Lists.newArrayList("1968438358@qq.com");
        List<String> ccUsers = Lists.newArrayList("2478926200@qq.com");
        String subject = "excel附件邮件";
        String content = new StringBuilder()
                .append("<html>")
                .append("<body>")
                .append("<p>邮件内容为html字符串，附件为excel</p>")
                .append("</body>")
                .append("</html>").toString();

        MailReq.Attachment attachment = MailReq.Attachment.builder()
                .attachmentName("2021-09-29_邮件附件过长测试邮件附件过长测试邮件附件过长测试.xlsx")
                .attachmentBytes(bytes)
                .build();

        MailReq mailReq = MailReq.builder()
                .toUsers(toUsers)
                .ccUsers(ccUsers)
                .subject(subject)
                .content(content)
                .attachments(Lists.newArrayList(attachment))
                .build();
        mailUtils.sendHtmlAndAttachmentsMail(mailReq);
    }

    @Override
    public void sendMultiAttachmentMail() {
        List<String> toUsers = Lists.newArrayList("1968438358@qq.com");
        List<String> ccUsers = Lists.newArrayList("2478926200@qq.com");
        String subject = "多附件邮件";
        String content = "多附件邮件内容";

        ClassPathResource imageResource = new ClassPathResource("/static/a.jpg");
        ClassPathResource imageResource2 = new ClassPathResource("/static/b.jpg");

        MailReq.Attachment attachment1 = null;
        MailReq.Attachment attachment2 = null;
        try {
            // 其实 messageHelper.addAttachment(fileName, resource) 中第二个参数可以直接传入 ClassPathResource，
            // 但是我们封装的 mailUtils.sendHtmlAndAttachmentsMail(mailReq) 参数接收的是附件的字节，没有接收 InputStream，因为要考虑关闭流，所以才接收byte[]
            // 这样谁调用该工具类，自己就去关闭流。这样更好一点
            attachment1 = MailReq.Attachment.builder()
                    .attachmentName("风景1.jpg")
                    .attachmentBytes(toByteArray(imageResource.getInputStream()))
                    .build();

            attachment2 = MailReq.Attachment.builder()
                    .attachmentName("风景2.jpg")
                    .attachmentBytes(toByteArray(imageResource2.getInputStream()))
                    .build();

            MailReq mailReq = MailReq.builder()
                    .toUsers(toUsers)
                    .ccUsers(ccUsers)
                    .subject(subject)
                    .content(content)
                    .attachments(Lists.newArrayList(attachment1, attachment2))
                    .build();
            mailUtils.sendHtmlAndAttachmentsMail(mailReq);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    /**
     * InputStream 转字节
     *
     * @param input
     * @return
     * @throws IOException
     */
    private static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}
